<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\MemberSite;
use app\api\model\User;
use app\api\model\UserTbOauth;
use app\api\model\UserTbOrder;
use app\api\model\Mp;
use app\BaseController;

class Sync extends BaseController

{
    public function order1()
    {
//     1、  按照订单创建时间获取渠道订单---利用接口一
//    每隔2分钟调用1次订单接口，获取最近5分钟或者10分钟内的订单创建数据，注意数据去重。获取的数据中包含全部订单付款订单和大部分失效订单。
//    注意：每隔2分钟调用1次订单接口。计算下来每天大约调用1000次。
        $start_time = date("Y-m-d%20H:i:s", strtotime("-180 minute"));
        $end_time = date('Y-m-d%20H:i:s');
        $useroauth = UserTbOauth::select()->toArray();
        foreach ($useroauth as $value) {

            $sid = $value['sid'];
            $url = 'https://api.zhetaoke.com:10001/api/open_dingdanchaxun2.ashx?appkey=47117b1f637b4986bae65cab9b4df54f&sid=' . $sid . '&start_time=' . $start_time . '&end_time=' . $end_time . '&signurl=1&query_type=1';
            $res = https_request($url);
//            var_dump($url);
            $outopt = json_decode($res, true);
            $res = https_request($outopt['url']);
            $res = json_decode($res, true);

            $this->getinfodata($value['uid'], $res);

        }

    }

    private function getinfodata($uid, $data)
    {
        dump($data);
        $data = $data['tbk_sc_order_details_get_response']['data']['results'];
        if ($data) {
            $data = $data['publisher_order_dto'];
            foreach ($data as $value) {
                $value['uid'] = $uid;
                $dataaaa = UserTbOrder::where('trade_id', $value['trade_id'])->find();
                if (!$dataaaa) {
                    $value['tk_create_time'] = strtotime($value['tk_create_time']);
                    if ($value['tk_status'] == 12) {
                        $value['tb_paid_time'] = strtotime($value['tb_paid_time']);
                    }
                    UserTbOrder::create($value);
                } else {
                    $value['tk_create_time'] = strtotime($value['tk_create_time']);
                    if ($value['tk_status'] == 12) {
                        $value['tb_paid_time'] = strtotime($value['tb_paid_time']);
                    }
                    UserTbOrder::update($value, ['id' => $dataaaa['id']]);
                }
            }
        }
    }

    public function order2()
    {
//     * 2、  按照订单结算时间获取结算的渠道订单---利用接口一
//    * 每隔2分钟调用1次订单接口，获取最近5分钟或者10分钟内的订单结算数据，注意数据去重。获取的数据中包含全部订单结算订单。
//    * 注意：每隔2分钟调用1次订单接口。计算下来每天大约调用1000次。
        $start_time = date("Y-m-d%20H:i:s", strtotime("-180 minute"));
        $end_time = date('Y-m-d%20H:i:s');
        $useroauth = UserTbOauth::select()->toArray();
        foreach ($useroauth as $value) {
            $sid = $value['sid'];
            $url = 'https://api.zhetaoke.com:10001/api/open_dingdanchaxun2.ashx?appkey=47117b1f637b4986bae65cab9b4df54f&sid=' . $sid . '&start_time=' . $start_time . '&end_time=' . $end_time . '&signurl=1&query_type=3';
            $res = https_request($url);
            $outopt = json_decode($res, true);
            $res = https_request($outopt['url']);
            $res = json_decode($res, true);
            $this->getinfodata($value['uid'], $res);

        }


    }

    public function order3()
    {

//     3、  按照订单创建时间获取前三天的渠道订单—利用接口二
//    * 调用订单接口二，每天凌晨2点左右，按照订单创建时间获取昨天、前天、大前天的订单数据，注意数据去重。获取的数据中包含遗漏的失效订单数据。注意：每天凌晨2点左右调用3次订单接口。计算下来每天大约调用3次。
//        https://api.zhetaoke.com:10001/api/open_dingdanchaxun2_piliang.ashx?appkey=47117b1f637b4986bae65cab9b4df54f&sid=&start_time=2020-08-27&query_type=1&tk_status=&order_scene=2&signurl=1
        $start_time = date("Y-m-d", strtotime("-1 day"));
        $query_type = '1';
        $useroauth = UserTbOauth::select()->toArray();
        foreach ($useroauth as $value) {

            $this->getdaydata($value['uid'], $value['sid'], $start_time, $query_type);
        }

    }

    private function getdaydata($uid, $sid, $start_time, $query_type = '')
    {

        $url = 'https://api.zhetaoke.com:10001/api/open_dingdanchaxun2_piliang.ashx?interval=20&appkey=47117b1f637b4986bae65cab9b4df54f&sid=' . $sid . '&start_time=' . $start_time . '&query_type=1&tk_status=&order_scene=2&signurl=1';

        $res = https_request($url);

        $res = json_decode($res, true);

        foreach ($res as $value) {

            $resvalue = https_request($value['url']);
            $resvalue = json_decode($resvalue, true);

            $this->getinfodata($uid, $resvalue);
        }

    }

    public function order4()
    {
        /**
         *  按照订单结算时间获取前三天的渠道订单—利用接口二
         * 调用订单接口二，每天凌晨2点左右，按照订单创建时间获取昨天、前天、大前天的订单数据，注意数据去重。获取的数据中包含遗漏的结算订单数据。
         * 注意：每天凌晨2点左右调用3次订单接口。计算下来每天大约调用3次。
         */
        $start_time = date("Y-m-d", strtotime("-1 day"));
        $query_type = '3';
        $useroauth = UserTbOauth::select()->toArray();
        foreach ($useroauth as $value) {

            $this->getdaydata($value['uid'], $value['sid'], $start_time, $query_type);

        }
    }


    //&sid=63142
    //&tao_id=1118031059
    //&tao_nick=tb95714_2013
    //&auth_time=1629385937
    //&expire_time=1631977937
    //&token=e24ccdd8e95b7ac9c409831aa0dfda85

    public function order5()
    {
        /**
         *  维权订单获取—利用接口二
         *  淘宝联盟每月20日发佣金后，利用接口二，按照订单结算时间获取全部结算订单，结算订单返回的字段“refund_tag”,值为1表示维权订单，
         * 此状态非实时数据，每个月给用户结算前统一批量获取一下，更新本地订单状态为“订单维权”即可。
         * 注意：每个月给用户结算前统一获取一次。计算下来每月需要调用30次订单接口，调用1次获取1天数据。
         */


    }

    public function indexss()
    {
        die;
        $client = new \dtkapi\GetOrderDetails();
        $client->setAppKey('60a9ea54efead');
        $client->setAppSecret('f0afa267225eb1c42887cc81e4ac06b3');
        $client->setVersion('v1.0.0');

        $startTime = date("Y-m-d H:i:s", strtotime("-180 minute"));
        $endTime = date("Y-m-d H:i:s");

        // $startTime  ='2021-08-05 15:15:35';
        // $endTime    ='2021-08-05 15:28:35';

        $res = $client->setParams(['queryType' => 4, 'startTime' => $startTime, 'endTime' => $endTime])->request();

        //$res='{"requestId":"f74dd608f29db02aafe949d9ddf34733","time":1628144686541,"code":0,"msg":"成功","data":{"has_next":false,"has_pre":false,"page_no":1,"page_size":20,"position_index":"1628144222_2m2dPbkbHm82|1628144222_2m2dPbkbHm82","results":{"publisher_order_dto":[{"adzone_id":111116100179,"adzone_name":"返利","alimama_rate":"10.00","alimama_share_fee":"0.38","alipay_total_price":"18.90","click_time":"2021-07-26 09:51:39","deposit_price":"0.00","flow_source":"--","income_rate":"20.01","item_category_name":"粮油调味/速食/干货/烘焙","item_id":614189681721,"item_img":"//img.alicdn.com/tfscom/i3/2204174570383/O1CN01rvZJRj1EhSN1CvKQV_!!0-item_pic.jpg","item_link":"http://item.taobao.com/item.htm?id=614189681721","item_num":1,"item_price":"59.90","item_title":"螺满地广西螺蛳粉300g整箱装 柳州正宗包邮袋装螺狮粉螺丝粉包邮","order_type":"天猫","pay_price":"18.90","pub_id":40796886,"pub_share_fee":"3.78","pub_share_pre_fee":"3.78","pub_share_rate":"100.00","refund_tag":0,"seller_nick":"螺满地旗舰店","seller_shop_title":"螺满地旗舰店","site_id":2206000447,"site_name":"菲林","subsidy_fee":"0.00","subsidy_rate":"0.00","subsidy_type":"--","tb_deposit_time":"--","tb_paid_time":"2021-07-26 09:54:20","terminal_type":"无线","tk_commission_fee_for_media_platform":"0.00","tk_commission_pre_fee_for_media_platform":"0.00","tk_commission_rate_for_media_platform":"0.00","tk_create_time":"2021-07-26 09:54:28","tk_deposit_time":"--","tk_earning_time":"2021-08-05 14:17:02","tk_order_role":2,"tk_paid_time":"2021-07-26 09:54:30","tk_status":12,"tk_total_rate":"20.01","total_commission_fee":"3.78","total_commission_rate":"20.01","trade_id":"1976900004143320016","trade_parent_id":"1976900004143320016","modified_time":"2021-08-05 14:17:02"}]}}}';
        $res = json_decode($res);
        $data = $res->data->results->publisher_order_dto;

        dump($data);

        if ($data) {
            $Ordermodel = new UserTbOrder();
            //循环下载订单数据
            foreach ($data as $value) {
                $dataaaa = $Ordermodel->where('trade_id', $value->trade_id)->find();

                //dump($value->trade_parent_id);
                if ($dataaaa) {
                    //更新数据判断状态为收货，对比数据库状态不一样就修改一样就跳过，为退款对比数据库状态
                    //3：订单结算 12：订单付款， 13：订单失效，14：订单成功
                    if ($dataaaa->status == $value->tk_status) {
                        //var_dump($dataaaa->status);
                        //  $this->wxtotextmsg($dataaaa->openid,'订单失效\n');
                    } else {
                        if ($value->tk_status == '12') {
                            //订单付款
                            var_dump('订单付款');
                            //$this->wxtotextmsg($dataaaa->openid,'订单付款\n'.$value->trade_parent_id.'\n商品名称\n'.$value->item_title);
                            $data = ['id' => $dataaaa->id, 'status' => $value->tk_status];
                            $res = $Ordermodel->Update($data);

                        } elseif ($value->tk_status == '13') {
                            //订单失效
                            var_dump('订单失效');
                            // $this->wxtotextmsg($dataaaa->openid,'订单失效\n'.$value->trade_parent_id.'\n商品名称\n'.$value->item_title);

                            $data = ['id' => $dataaaa->id, 'status' => $value->tk_status];
                            $res = $Ordermodel->Update($data);

                        } elseif ($value->tk_status == '14') {
                            //订单完成


                            //$this->wxtotextmsg($dataaaa->openid,'订单完成\n'.$value->trade_parent_id.'\n商品名称\n'.$value->item_title);
                            $data = ['id' => $dataaaa->id, 'status' => $value->tk_status];
                            $res = $Ordermodel->Update($data);

                        } elseif ($value->tk_status == '3') {
                            //订单结算

                            //处理冻结和结算方法
                            //$this->wxtotextmsg($dataaaa->openid,'订单结算\n'.$value->trade_parent_id.'\n商品名称\n'.$value->item_title);
                            $data = ['id' => $dataaaa->id, 'status' => $value->tk_status];
                            $res = $Ordermodel->Update($data);

                        }

                        // if($res){
                        //     //获取更新之后的数据
                        //     $infodata=$Ordermodel->where('id', $res->id)->find();
                        //     //判断订单是否有用户
                        //     if($infodata->openid){
                        //         $this->wxtotextmsg($infodata->openid,'订单更新状态成功');
                        //         $Usermodel=new User();
                        //         //默认设置以后迭代修改比例
                        //         $bil=70;
                        //         $effec_money=$value->pub_share_pre_fee*$bil/100;

                        //         $Usermodel->where('openid', $infodata->openid )->inc('effec_money',$effec_money)->update();
                        //         $Ordermodel->where('openid', $infodata->openid )->update(['to_user_money'=>$effec_money]);
                        //         //$data=$Usermodel->select();

                        //     }

                        // }

                    }

                } else {

                    //添加数据
                    if ($value->tk_status != '13') {

                        //自动绑定微信或者按查询绑定方法
                        $orderinfo = substr($value->trade_parent_id, -6, 6);
                        $Userinfodata = User::where('tb_order_sixbit', $orderinfo)->find();

                        if ($Userinfodata) {
                            $TempData = $value->alipay_total_price * $value->total_commission_rate * 70 / 10000;
                            //把下单佣金写入用户数据库中
                            User::where('openid', $Userinfodata->openid)->inc('effec_money', $TempData)->inc('order_num')->update();

                            $Ordermodel->create([
                                'trade_parent_id' => $value->trade_parent_id,//下单的订单号
                                'trade_id' => $value->trade_id,//下单的子订单号
                                'order_type' => '淘宝', //平台 .order_type”
                                'title' => $value->item_title,
                                'openid' => $Userinfodata->openid,
                                'item_id' => $value->item_id,//商品ID
                                'refund_tag' => $value->refund_tag,
                                'paid_time' => strtotime($value->tk_create_time),//付款时间 .tk_paid_time”
                                'total_price' => $value->alipay_total_price,//付款总价
                                'status' => $value->tk_status,//订单状态
                                'pub_share_pre_fee' => $value->pub_share_pre_fee,//付款预估收入
                                'total_commission_fee' => $value->total_commission_fee,//佣金金额
                                'total_commission_rate' => $value->total_commission_rate,//佣金比率
                            ]);

                        } else {

                            $Ordermodel->create([
                                'trade_parent_id' => $value->trade_parent_id,//下单的订单号
                                'trade_id' => $value->trade_id,//下单的子订单号
                                'order_type' => $value->order_type, //平台 .order_type”
                                'title' => $value->item_title,
                                'item_id' => $value->item_id,//商品ID
                                'refund_tag' => $value->refund_tag,
                                'paid_time' => strtotime($value->tk_create_time),//付款时间 .tk_paid_time”
                                'total_price' => $value->alipay_total_price,//付款总价
                                'status' => $value->tk_status,//订单状态
                                'pub_share_pre_fee' => $value->pub_share_pre_fee,//付款预估收入
                                'total_commission_fee' => $value->total_commission_fee,//佣金金额
                                'total_commission_rate' => $value->total_commission_rate,//佣金比率
                            ]);

                        }


                    }


                }

            }


        }

    }

    public function tbopen()
    {
        $arr['uid'] = session('admin.id');
        $arr['sid'] = $this->request->param('sid');
        $arr['tao_id'] = $this->request->param('tao_id');
        $arr['tao_nick'] = $this->request->param('tao_nick');
        $arr['auth_time'] = $this->request->param('auth_time');
        $arr['expire_time'] = $this->request->param('expire_time');
        $arr['token'] = $this->request->param('token');
        if ($arr['sid'] != '') {
            $siddata = UserTbOauth::where('sid', $arr['sid'])->find();

            if ($siddata) {
                //更新数据

                if (UserTbOauth::update($arr, ['id' => $siddata->id])) {
                    return view();
                } else {
                    return '更新授权失败';
                }

            } else {
                //添加数据
                if (UserTbOauth::create($arr)) {
                    return view();
                } else {
                    return '授权失败';
                }
            }


        } else {
            return '请重新操作';
        }

    }

    public function cs()
    {$Systemdata = MemberSite::where('id', 1)->field('draw_limit_money,draw_method,draw_auto_money')->find();


        dump($Systemdata);


    }

}